package com.qeeyou.apps.android.craftsman.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.google.gson.Gson;
import com.qeeyou.apps.android.craftsman.po.CommonInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttpUtil {

    private static String TAG = "OKHttpUtil";

    public static int NET_WIFI = 1;
    public static int NET_MOBILENET = 2;
    public static int NET_NULL = 3;

    public static String URL_ENCODEING = "utf-8";

    /**
     * 获取网络状态
     *
     * @param context
     * @return
     */
    public static int getNetWorkType(Context context) {
        try {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
            if (info == null) {
                return NET_NULL;
            }
            int netType = info.getType();
            if (netType == ConnectivityManager.TYPE_WIFI) {
                return NET_WIFI;
            } else if (netType == ConnectivityManager.TYPE_MOBILE) {
                return NET_MOBILENET;
            } else {
                return NET_NULL;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return NET_NULL;
        }

    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        int netType = getNetWorkType(context);
        if (netType == NET_NULL) {
            return false;
        } else {
            return true;
        }
    }

    //用get方法下载信息， return String or null
    public static String downWithGetMethod(String url, Map<String, String> paraMap, Map<String, String> headerMap) {
        String returnString = null;
        OkHttpClient client = new OkHttpClient();
        try {
            if (paraMap != null && paraMap.size() > 0) {
                String paraString = "";
                for (Map.Entry<String, String> entry : paraMap.entrySet()) {
                    if (paraString.equalsIgnoreCase("")) {
                        paraString = entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), URL_ENCODEING);
                    } else {
                        paraString = paraString + "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), URL_ENCODEING);
                    }
                    Log.d(TAG, entry.getKey() + ":" + entry.getValue());
                }
                url = url + "?" + paraString;
            }
            Request.Builder builder = new Request.Builder().url(url);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            Request request = builder.build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                returnString = response.body().string();
            } else {
                CommonInfo errorInfo = new CommonInfo();
                errorInfo.setStatus(response.code() + "");
                errorInfo.setMessage(response.message());
                byte[] data = new Gson().toJson(errorInfo).getBytes();
                returnString = new String(data, URL_ENCODEING);
            }
        } catch (UnsupportedEncodingException e) {
            returnString = null;
        } catch (IOException e) {
            returnString = null;
        } catch (Exception e) {
            returnString = null;
        } finally {

        }
        return returnString;
    }

    public static String downWithPostMethod(String url, Map<String, String> paraMap, Map<String, String> headerMap) {
        String returnString = null;
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
        OkHttpClient client = clientBuilder.build();
        try {
            FormBody.Builder requestBody = new FormBody.Builder();
            if (paraMap != null && paraMap.size() > 0) {
                for (Map.Entry<String, String> entry : paraMap.entrySet()) {
                    requestBody.add(entry.getKey(), entry.getValue());
                    Log.d(TAG, entry.getKey() + ":" + entry.getValue());
                }
            }
            Request.Builder builder = new Request.Builder().url(url);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            Request request = builder.post(requestBody.build()).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                returnString = response.body().string();
            } else {
                CommonInfo errorInfo = new CommonInfo();
                errorInfo.setStatus(response.code() + "");
                errorInfo.setMessage(response.message());
                byte[] data = new Gson().toJson(errorInfo).getBytes();
                returnString = new String(data, URL_ENCODEING);
            }
        } catch (UnsupportedEncodingException e) {
            returnString = null;
        } catch (IOException e) {
            returnString = null;
        } catch (Exception e) {
            returnString = null;
        } finally {

        }
        return returnString;
    }

    public static String downWithPostJsonMethod(String url, Map<String, String> paraMap, Map<String, String> headerMap) {
        String returnString = null;
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
        OkHttpClient client = clientBuilder.build();
        try {
            RequestBody requestBody;
            if (paraMap != null && paraMap.size() > 0) {
                String paramJson = new Gson().toJson(paraMap);
                requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), paramJson);
            } else {
                requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), "{}");
            }
            Request.Builder builder = new Request.Builder().url(url);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            Request request = builder.post(requestBody).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                returnString = response.body().string();
            } else {
                CommonInfo errorInfo = new CommonInfo();
                errorInfo.setStatus(response.code() + "");
                errorInfo.setMessage(response.message());
                byte[] data = new Gson().toJson(errorInfo).getBytes();
                returnString = new String(data, URL_ENCODEING);
            }
        } catch (UnsupportedEncodingException e) {
            returnString = null;
        } catch (IOException e) {
            returnString = null;
        } catch (Exception e) {
            returnString = null;
        } finally {

        }
        return returnString;
    }

    public static String uploadFile(String url, List<String> filePaths, Map<String, String> headerMap) {
        String returnString = null;
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
        OkHttpClient client = clientBuilder.build();
        try {
            Request.Builder builder = new Request.Builder().url(url);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
            MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (String filePath : filePaths) {
                File file = new File(filePath);
                if(file != null) {
                    requestBody.addFormDataPart("file", "", RequestBody.create(MEDIA_TYPE_PNG, file));
                }
            }
            Request request = builder.post(requestBody.build()).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                returnString = response.body().string();
            } else {
                CommonInfo errorInfo = new CommonInfo();
                errorInfo.setStatus(response.code() + "");
                errorInfo.setMessage(response.message());
                byte[] data = new Gson().toJson(errorInfo).getBytes();
                returnString = new String(data, URL_ENCODEING);
            }
        } catch (UnsupportedEncodingException e) {
            returnString = null;
        } catch (IOException e) {
            returnString = null;
        } catch (Exception e) {
            returnString = null;
        } finally {

        }
        return returnString;
    }

}
